package top.lyjwn.todo.aop.interceptor;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.lyjwn.todo.aop.token.Login;
import top.lyjwn.todo.aop.token.Token;
import top.lyjwn.todo.common.context.SpringContext;
import top.lyjwn.todo.common.template.R;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 身份验证拦截器
 *
 * @author luoyujie
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    private final Logger log = LoggerFactory.getLogger("error");

    @Autowired
    private Token token;




    // 在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object object) {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        if (this.token == null) {// 解决token为null无法注入问题
            this.token = (Token) SpringContext.getBean("token", httpServletRequest);
            if (this.token == null) {
                toJson(httpServletResponse, R.init().error(411, "未发现token"));
                return false;
            }
//			BeanFactory factory = WebApplicationContextUtils
//					.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
//			this.token = (Token) factory.getBean("token");
        }
        R authenticationInterceptor = this.token.authenticationInterceptor(token,
                httpServletResponse, object);
        JSONObject login = this.token.getLogin();
        if (login != null) {
            if (!this.token.IsJwt()) {
                this.token.postpone(token);
            } else {
                String token2 = this.token.buildToken(login);
                httpServletResponse.setHeader("token", token2);
            }
        }

        if (authenticationInterceptor.isDone()) {
            return true;
        } else {
            toJson(httpServletResponse, authenticationInterceptor);
            return false;
        }

    }



    private void toJson(HttpServletResponse response, R result) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            result.setDone(false);
            result.setCode(401);
            result.setMsg(result.getMsg() == null ? "用户未登录" : result.getMsg());
            out = response.getWriter();
            out.append(JSONObject.toJSONString(result));
            out.flush();
        } catch (IOException e) {
            log.error("拦截器输出json错误:" + e.getMessage());
        }
    }

}
